import fs from 'node:fs/promises';
import {getNewPage, launchChrome, closeChrome} from "./utils/chrome.js";
import {getServiceUrlUrl} from "./utils/links.js";
import { sleep } from "./utils/index.js";
import config from "./config.js";

const content = await fs.readFile('./input.txt', 'utf8');

export const UrlReg = new RegExp(
  `((http|ftp|https)://)((localhost)|([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?`,
  "gi"
);

const rows = content.split('\n');

await launchChrome();

for (const row of rows) {
  const urls = row.match(UrlReg);
  const item = [row]
  if(urls && urls.length > 0){
    const url = urls[0];
    try {
      const serviceUrl = await getServiceUrlUrl(url);
      console.log(`${url}获取客服地址成功：${serviceUrl}`);
      await automationPage(serviceUrl, config.type);
      item.push('成功');
    }catch(err){
      const msg = err.message.replaceAll('\n', '')
      console.error(msg)
      item.push('失败');
      item.push(msg);
    }
    await fs.appendFile('./output.txt', item.join('----') + '\n', 'utf8');
  }
}
await closeChrome();


async function automationPage(url, type) {
  const page = await getNewPage();
  try {
    await page.goto(url, {
      // waitUntil: 'networkidle0', // 等待网络空闲（推荐）
      waitUntil: 'networkidle2',
      timeout: 60000, // 超时时间，默认 30 秒，可以调大
    });
    console.log('网页加载完成');

    await sleep(1000);

    const modalContent = await page.evaluate(() => {
      return document.querySelector('.Modal')?.textContent;
    });

    if(modalContent) {
      throw new Error(modalContent)
    }

    if(type === 'star') {
      await star(page);
    }
    if(type === 'coupon') {
      await coupon(page);
    }
  } finally {
    page.close();
  }
}

async function star(page) {

  const quickBtn = await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('.QuickReply');
    return Array.from(buttons).find((btn) => btn.textContent.trim() === '星星延期');
  }, { timeout: 10 * 10000 });

  console.log('点击【星星延期】')
  await quickBtn.asElement().click();

  const searchBtn = await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('.Btn--primary');
    return Array.from(buttons).find((btn) => btn.textContent.trim() === '查询可延期好礼星星');
  }, { timeout: 10 * 10000 });

  console.log('点击【查询可延期好礼星星】')
  await searchBtn.asElement().click();

  await sleep(2000);

  const lastMessage = await getLastMessage(page);

  if(lastMessage.includes('无法再次发起延期')) {
    throw new Error(lastMessage);
  }

  const applyCard = await page.evaluateHandle(() => {
    const messageCards = document.querySelectorAll('.Message.left');
    const prevIndex = Array.from(messageCards).findIndex(v => v.textContent.includes('您账户内可在线申请延期的好礼星星如下'))
    return messageCards[prevIndex + 1];
  });

  const applyBtnHandle = await applyCard.evaluateHandle((card) => {
    const buttons = card.querySelectorAll('.Btn--primary');
    return Array.from(buttons).find((btn) => btn.textContent.trim() === '申请延期');
  });

  const applyBtn = applyBtnHandle.asElement();

  if(!applyBtn) {
    throw new Error('不可申请延期：' + await applyCard.evaluate(el => el.textContent));
  }

  console.log('点击【申请延期】')
  await applyBtn.click();
  await sleep(2000);
  const msg = await applyCard.evaluate(el => el.textContent.trim());

  if(msg.includes('已过有效期的好礼星星进行延期')) {
    return msg
  }else {
    throw new Error(msg);
  }
}


async function coupon(page) {

  const quickBtn = await page.waitForFunction(() => {
    const buttons = document.querySelectorAll('.QuickReply');
    return Array.from(buttons).find((btn) => btn.textContent.trim() === '好礼延期');
  }, { timeout: 10 * 10000 });

  console.log('点击【好礼延期】')
  await quickBtn.asElement().click();

  await sleep(1000);

  const lastMessage = await getLastMessage(page);

  if(lastMessage.includes('没有查询到')) {
    throw new Error(lastMessage);
  }

  const applyCard = await page.evaluateHandle(() => {
    const messageCards = document.querySelectorAll('.Message.left');
    const prevIndex = Array.from(messageCards).findIndex(v => v.textContent.includes('您帐户内可在线申请延期的'))
    return messageCards[prevIndex + 1];
  });

  const applyBtnHandle = await applyCard.evaluateHandle((card) => {
    const buttons = card.querySelectorAll('.Btn--primary');
    return Array.from(buttons).find((btn) => btn.textContent.trim() === '申请延期');
  });

  const applyBtn = applyBtnHandle.asElement();

  if(!applyBtn) {
    throw new Error('不可申请延期：' + await applyCard.evaluate(el => el.textContent));
  }

  console.log('点击【申请延期】')
  await applyBtn.click();
  await sleep(2000);
  const msg = await getLastMessage(page);
  if(msg.includes('已为您的好礼延')) {
    return msg
  }else {
    throw new Error(msg);
  }
}

async function getLastMessage(page) {
  return await page.evaluate(() => {
    const messageCards = document.querySelectorAll('.Message.left');
    for (let i = messageCards.length - 1; i >= 0; i--) {
      const text = messageCards[i].textContent.trim();
      if (!text.includes('满意度')) {
        return text;
      }
    }
    return null;
  });
}
